<template>
	<view @touchmove.stop.prevent>
		<view class="wd-sku-popup" :class="{ 'wd-sku-popup__show': show }" :style="{ zIndex: zIndex}">
			<view class="wd-sku-header">
				<image class="wd-sku-header__thumb" :src="goodsImage" mode="aspectFill">
				</image>
				<view class="wd-sku-header__body">
					<view class="wd-sku-header__body-price">¥{{goodsPrice}}</view>
					<view class="wd-sku-header__body-sales">已售{{goodsSales}}件</view>
				</view>
			</view>
			<view class="wd-sku-specs" v-if="hasSku">
				<block v-for="(skuTreeItem,skuTreeIndex) in skuTree" :key="skuTreeIndex">
					<view class="wd-sku-specs__label">{{ skuTreeItem.k }}</view>
					<view class="wd-sku-specs__attr">
						<view class="wd-sku-specs__item" v-for="(skuValue,skuValueIdx) in skuTreeItem.v"
							:key="skuValueIdx" :class="{
								'wd-sku-specs__item--active': choosed(skuValue.id,skuTreeItem.k_s),
								'wd-sku-specs__item--disabled': !choosable(skuValue.id,skuTreeItem.k_s)
							 }" @click="onSkuSelect(skuValue,skuTreeItem.k_s)">{{ skuValue.name }}</view>
					</view>
				</block>
			</view>
			<view class="wd-sku-stepper">
				<view class="wd-sku-stepper__label">数量</view>
				<u-number-box class="wd-sku-stepper__number" size="24" input-height="44" :min="1" :max="stepperLimit"
					v-model="selectedNum" @change="onStepperChange"></u-number-box>
			</view>
			<view class="wd-sku-toolbar">
				<view class="wd-sku-toolbar__btn" @click="onAddCart">加入购物车</view>
				<view class="wd-sku-toolbar__btn" @click="onBuy">立即购买</view>
			</view>
		</view>
		<view class="wd-sku-mask" :class="[show ? 'wd-sku-mask__show' : '']" :style="{ zIndex: (zIndex-1) }"
			@tap="handleClose"></view>
	</view>
</template>

<script>
	import {
		LIMIT_TYPE,
		UNSELECTED_SKU_VALUE_ID,
		skuToast,
		isDef,
		isAllSelected,
		isSkuChoosable,
		getSkuComb,
		getSelectedSkuValues,
		getSelectedSkuImg
	} from './skuHelper.js';
	const {
		QUOTA_LIMIT,
		STOCK_LIMIT
	} = LIMIT_TYPE;
	export default {
		name: 'wdSku',
		props: {
			//控制显示
			show: {
				type: Boolean,
				default: false
			},
			zIndex: {
				type: [Number, String],
				default: 997
			},
			goods: { // 商品信息
				type: Object,
				default () {
					return {};
				}
			},
		},
		data() {
			return {
				selectedSku: {},
				selectedNum: 1,
				// 购买限制类型: 限购/库存
				limitType: STOCK_LIMIT

			}
		},
		watch: {
			// skuTree(val) {
			//     this.resetSelectedSku(val);
			// }
		},
		computed: {
			sku() { // sku
				return this.goods.sku || {};
			},
			hasSku() {
				// return !this.goods.none_sku;
				return this.goods.hasOwnProperty('sku');
			},
			skuTree() { // sku规格类目与其值的从属关系
				return this.sku.tree || [];
			},
			skuList() { // sku所有的组合列表
				return this.sku.list || [];
			},
			initialSku() { // sku的默认选择
				return this.sku.initial || {};
			},
			isSkuCombSelected() {
				return isAllSelected(this.skuTree, this.selectedSku);
			},
			selectedSkuComb: {
				get() {
					if (!this.hasSku) {
						return this.goods.spec[0];
					}
					if (this.isSkuCombSelected) {
						return getSkuComb(this.skuList, this.selectedSku);
					}
					return null;
				},
				set(val) {}
			},

			quota() {
				// 判断每个规格是否限购
				if (this.hasSku && this.selectedSkuComb && this.selectedSkuComb.limit_num) {
					return this.selectedSkuComb.limit_num;
				}
				return this.goods.quota || 0;
			},
			quotaUsed() {
				return this.goods.quotaUsed || 0;
			},
			stepperLimit() {
				const quotaLimit = this.quota - this.quotaUsed;
				let limit;
				let stock = this.selectedSkuComb ? this.selectedSkuComb.stock_num : this.selectedNum;

				// 无限购时直接取库存，有限购时取限购数和库存数中小的那个
				if (this.quota > 0 && quotaLimit <= stock) {
					// 修正负的limit
					limit = quotaLimit < 0 ? 0 : quotaLimit;
					this.limitType = QUOTA_LIMIT;
				} else {
					limit = stock;
					this.limitType = STOCK_LIMIT;
				}
				if (limit <= this.selectedNum) {
					this.selectedNum = limit
				} else if (limit > 0 && this.selectedNum == 0) {
					this.selectedNum = 1
				}
				return limit;
			},

			goodsPrice() {
				if (this.selectedSkuComb) {
					return ((this.selectedSkuComb.goods_price * 100) / 100).toFixed(2);
				}
				// sku.price是一个格式化好的价格区间
				return this.goods.spec[0].goods_price || '';
			},
			goodsSales() {
				if (this.selectedSkuComb) {
					return this.selectedSkuComb.goods_sales;
				}
				return this.goods.sales_actual;
			},
			goodsImage() {
				return getSelectedSkuImg(this.skuList, this.selectedSku) || this.goods.image;
			},


		},
		created() {
			this.resetSelectedSku(this.skuTree);
		},
		methods: {
			handleClose() {
				if (!this.show) {
					return;
				}
				this.$emit('close', {});
			},
			resetSelectedSku(skuTree) {
				this.selectedSku = {};

				// 重置 selectedSku
				skuTree.forEach(item => {
					this.selectedSku[item.k_s] = this.initialSku[item.k_s] || UNSELECTED_SKU_VALUE_ID;
				});

				// 只有一个 sku 规格值时默认选中
				skuTree.forEach(item => {
					const key = item.k_s;
					const valueId = item.v[0].id;
					if (
						item.v.length === 1 &&
						isSkuChoosable(this.skuList, this.selectedSku, {
							key,
							valueId
						})
					) {
						this.selectedSku[key] = valueId;
					}
				});
			},
			choosed(skuValId, skuKeyStr) {
				return skuValId === this.selectedSku[skuKeyStr];
			},
			choosable(skuValId, skuKeyStr) {
				return isSkuChoosable(this.skuList, this.selectedSku, {
					key: skuKeyStr,
					valueId: skuValId
				});
			},
			onSkuSelect(skuValue, skuKeyStr) {
				// 点击已选中的sku时则取消选中
				this.selectedSku = this.selectedSku[skuKeyStr] === skuValue.id ? {
					...this.selectedSku,
					[skuKeyStr]: UNSELECTED_SKU_VALUE_ID
				} : {
					...this.selectedSku,
					[skuKeyStr]: skuValue.id
				};
				this.$emit('sku-selected', {
					skuValue,
					skuKeyStr: skuKeyStr,
					selectedSku: this.selectedSku,
					selectedSkuComb: this.selectedSkuComb
				});
			},
			onStepperChange(value) {
				this.$emit('stepper-change', value);
			},
			onAddCart() {
			    this.onBuyOrAddCart('add-cart');
			},
			onBuy() {
			    this.onBuyOrAddCart('buy-clicked');
			},
			onBuyOrAddCart(type) {
			    const error = this.validateSku();
			    if (error) {
			        skuToast(error);
			    } else {
					// console.log(this.getSkuData())
			        this.$emit(type, this.getSkuData());
			    }
			},
			validateSku() {
			    if (this.quota > 0 && (this.quota - this.quotaUsed) <= 0) {
			        return '商品已达最大限购无法购买啦';
			    }
			    if (this.selectedNum === 0) {
			        return '商品已经无法购买啦';
			    }
			    if (this.isSkuCombSelected) {
			        return '';
			    }
			    return '请先选择商品规格';
			},
			getSkuData() {
			    const selectedSkuValues = getSelectedSkuValues(this.skuTree, this.selectedSku);
			    return {
			        goodsId: this.goods.id,
			        selectedNum: this.selectedNum,
			        selectedSkuComb: this.selectedSkuComb,
			        selectedSkuValues
			    };
			},
		}
	}
</script>

<style lang="scss" scoped>
	.wd-sku-popup {
		width: 100%;
		min-height: 20rpx;
		padding: 0 24rpx;
		background: #FFFFFF;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		opacity: 0;
		transform: translate3d(0, 110%, 0);
		transform-origin: center;
		transition: all 0.3s ease-in-out;
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
		padding-bottom: env(safe-area-inset-bottom);

		&__show {
			opacity: 1;
			transform: translate3d(0, 0, 0);
		}
	}

	.wd-sku-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		transition: all 0.3s ease-in-out;
		opacity: 0;
		visibility: hidden;

		&__show {
			opacity: 1;
			visibility: visible;
		}
	}

	.wd-sku-header {
		display: flex;
		align-items: flex-end;
		margin-top: -66rpx;

		&__thumb {
			display: block;
			margin-right: 40rpx;
			width: 200rpx;
			height: 200rpx;
			border-radius: 24rpx;
		}

		&__body {
			flex: 1;
		}

		&__body-price {
			margin-bottom: 8rpx;
			line-height: 54rpx;
			font-size: 38rpx;
			font-weight: 500;
			color: #EE0000;
		}

		&__body-sales {
			margin-bottom: 10rpx;
			line-height: 30rpx;
			font-size: 22rpx;
			color: #999999;
		}
	}

	.wd-sku-specs {
		margin-top: 24rpx;
		border-top: 1rpx #EDEDED solid;
		padding-top: 24rpx;
		max-height: 60vh;
		overflow-x: hidden;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;

		&__label {
			line-height: 38rpx;
			font-size: 26rpx;
			color: #333333;
		}

		&__attr {
			margin-top: 10rpx;
			display: flex;
			flex-wrap: wrap;
		}

		&__item {
			margin-bottom: 24rpx;
			margin-right: 24rpx;
			padding: 0 20rpx;
			min-width: 160rpx;
			height: 56rpx;
			background: #F0F0F0;
			text-align: center;
			line-height: 56rpx;
			font-size: 26rpx;
			color: #333333;
			border-radius: 99px;
		}

		&__item--active {
			background: linear-gradient(131deg, #A36BFF 0%, #6D4BBE 100%);
			color: #FFFFFF;
		}

		&__item--disabled {
			opacity: .5;
		}
	}

	.wd-sku-stepper {
		border-top: 1rpx #EDEDED solid;
		padding: 25rpx 0;
		display: flex;
		align-items: center;

		&__label {
			flex: 1;
			line-height: 38rpx;
			font-size: 26rpx;
			color: #333333;
		}

		&__number {

			/deep/ .u-icon-minus,
			/deep/ .u-icon-plus {
				width: 44rpx !important;
				background: #E1E1E1 !important;
				border-radius: 50% !important;
			}

			/deep/ .u-icon-minus {
				background: #E1E1E1 !important;
			}

			/deep/ .u-icon-plus {
				background: linear-gradient(131deg, #A36BFF 0%, #6D4BBE 100%) !important;
				color: #FFFFFF !important;
			}

			/deep/ .u-number-input {
				background: transparent !important;
			}
		}
	}

	.wd-sku-toolbar {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		padding: 20rpx 0;
		background-color: #FFFFFF;

		&__btn {
			flex: 1;
			height: 90rpx;
			line-height: 90rpx;
			font-size: 32rpx;
			text-align: center;

			&:first-child {
				color: #6D4BBE;
				background: rgba(109, 75, 190, 0.15);
				border-radius: 49px 0px 0px 49px;
			}

			&:last-child {
				color: #FFFFFF;
				background: linear-gradient(131deg, #A36BFF 0%, #6D4BBE 100%);
				border-radius: 0 49rpx 49rpx 0;
			}

		}
	}
</style>
<style>
	/* .wd-sku-stepper__number /deep/ .u-icon-minus,
	.wd-sku-stepper__number /deep/ .u-icon-plus {
		width: 44rpx !important;
		background: #E1E1E1 !important;
		border-radius: 50% !important;
	}
	.wd-sku-stepper__number /deep/ .u-icon-minus {
		background: #E1E1E1 !important;
	}
	.wd-sku-stepper__number /deep/ .u-icon-plus {
		background: linear-gradient(131deg, #A36BFF 0%, #6D4BBE 100%) !important;
		color: #FFFFFF !important;
	}
	.wd-sku-stepper__number /deep/ .u-number-input {
		background: transparent !important;
	} */
</style>
